<template>
  <div>
    <!--头部：分类  增加 -->
    <div class="filter-container"><el-button type="primary" icon="el-icon-edit" @click="handleAdd">新增</el-button></div>

    <!-- 数据列表 编辑 删除 -->
    <div class="list-container">
      <el-table :data="dataList" fit highlight-current-row style="width: 100%;">
        <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.$index)">编辑</el-button>
            <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 数据量不多，这里就不进行分页处理了 -->
    </div>

    <!-- 编辑弹出框 -->
    <category-edit v-if="editDialogVisible" ref="editDialog" @refreshDataList="loadDataList" />
  </div>
</template>

<script>
import CategoryEdit from './components/CategoryEdit.vue';
import * as CategoryAPI from '@/api/category.js';
export default {
  name: 'categoryList',
  components: {
    CategoryEdit
  },
  data() {
    return {
      dataList: [], //列表数据
      editDialogVisible: false //编辑框
    };
  },

  created() {
    // 获取数据
    this.loadDataList();
  },

  methods: {
    // 获取列表数据
    loadDataList() {
      CategoryAPI.getCategoryList().then(result => {
        this.dataList = result.data;
      });
    },

    // 删除操作
    handleDelete(index) {
      // 二次确认删除
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 选择了确认，则删除后端数据库中的记录
          let id = this.dataList[index].id; //要删除记录的id
          CategoryAPI.deleteCategoryById(id)
            .then(() => {
              this.dataList.splice(index, 1); //同步列表中的记录
              this.$message.success('删除成功');
            })
            .catch(() => {});
        })
        .catch(() => {});
    },

    // 编辑操作
    handleUpdate(index) {
      const id = this.dataList[index].id;
      this.editDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.editDialog.init(id);
      });
    },

    // 触发增加按钮
    handleAdd() {
      this.editDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.editDialog.init();
      });
    }
  }
};
</script>

<style scoped></style>
